import functools

import logging

from flask import g
from flask import session, jsonify

from ihome_tenancy.models import User
from ihome_tenancy.utils.response_code import RET, ret_map


def is_login(view_func):
    @functools.wraps(view_func)
    def wrapper(*args, **kwargs):
        user_id = session.get('user_id')
        if user_id:
            try:
                user = User.query.get(user_id)
            except Exception:
                logging.error('查询数据库错误出错')
                return jsonify(code=RET.DATAERR, msg=ret_map[RET.DATAERR])
            if user:
                g.user = user
                return view_func(*args, **kwargs)

            return jsonify(code=RET.PARAMERR, msg=ret_map[RET.PARAMERR])

        return jsonify(code=RET.LOGINERR, msg=ret_map[RET.LOGINERR])

    return wrapper